package com.zhanglinwei.common;

import com.zhanglinwei.common.utils.RequestIdUtils;
import lombok.Getter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;

import java.util.Collection;

@Getter
public class Response<T> {

    protected final static String SUCCESS_CODE = "200";

    protected final String requestId;
    protected final String code;
    protected final String msg;
    protected final Boolean success;
    protected final T data;
    protected final Long pageOn;
    protected final Long pageSize;
    protected final Long total;

    protected Response(String code, String msg, boolean success, T data, long pageOn, long pageSize, long total) {
        this.requestId = RequestIdUtils.getRequestId();
        this.code = code;
        this.msg = msg;
        this.success = success;
        this.data = data;
        this.pageOn = pageOn;
        this.pageSize = pageSize;
        this.total = total;
    }

    public static <T> Response<T> success(){
        return success(null);
    }

    public static <T> Response<T> success(T data){
        return success(data, 0, 0, 0);
    }

    public static <T> Response<T> success(T data, long pageOn, long pageSize, long total){
        return of(SUCCESS_CODE, "SUCCESS", true, data, pageOn, pageSize, total);
    }

    public static <T> Response<T> fail(String errorCode, String errorMsg){
        return of(errorCode, errorMsg, false, null, 0, 0, 0);
    }

    private static <T> Response<T> of(String code, String msg, boolean success, T data, long pageOn, long pageSize, long total){
        return new Response<>(code, msg, success, data, pageOn, pageSize, total);
    }

    public static Boolean callSuccess(Response<?> response) {
        return response != null && SUCCESS_CODE.equals(response.getCode()) && BooleanUtils.isTrue(response.getSuccess());
    }

    public static Boolean isEmpty(Response<?> response) {
        if (!callSuccess(response)) {
            return true;
        }

        Object responseData = response.getData();
        if (responseData instanceof Collection) {
            return CollectionUtils.isEmpty((Collection<?>) responseData);
        }

        return responseData == null;
    }

    public static Boolean isNotEmpty(Response<?> response) {
        return !isEmpty(response);
    }

}
